<template>
  <div class="associatedBox">
    <el-button
      type="primary"
      size="small"
      @click="toRelationEvent"
    >
      {{$t('common.fields.eventContact.displayName')}}
    </el-button>
    <el-dialog :title="$t('common.fields.eventContact.displayName')" :visible.sync="dialogVisible" width="30%">
      <div class="label">{{$t('common.fields.eventContact.displayName')}}</div>
      <el-select
        @change="change"
        v-model="value"
        multiple
        :placeholder="$t('common.placeholder.inputContact')"
        v-loadmoreList="loadmoreList"
      >
        <el-option
          v-for="(item, index) in optionsList"
          :key="index"
          :label="item.eventNo"
          :value="item.id"
          style="height:auto;"
        >
          <div class="Info">
            <div class="Info1">{{ item.eventNo }}</div>
            <div class="Info2">{{$t('common.fields.customer.displayName')}}： {{ cusNameReg(item.cusName) }}</div>
            <div class="Info2">{{$t('common.fields.contact.displayName')}}： {{ item.lmName }}</div>
            <div class="Info2">{{$t('common.fields.phone.displayName')}}： {{ item.lmPhone }}</div>
          </div>
        </el-option>
      </el-select>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="Save">
          {{$t('common.base.confirm')}}
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as EventApi from '@src/api/EventApi.js';
import * as ImApi from '@src/api/ImApi.js';
export default {
  name: 'associated-events',
  props: {
    conversationId: [Number, String],
    bizType: {
      typeof: String,
      default: 'event',
    },
    bizRelInfos: {
      typeof: Array,
      default: () => [],
    },
    cusId: {
      typeof: [Number, String],
      default: '',
    },
    from: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogVisible: false,
      value: [],
      Timeout: null,
      list: [],
      bizRelList: [],
      params: {
        cusId: '',
        pageSize: 10,
        pageNum: 1,
      },
    };
  },
  watch: {
    cusId: {
      handler(val) {
        if (this.cusId) this.params.cusId = this.cusId;
        this.list = []
        this.params.pageNum = 1
        this.$nextTick(()=>{
          this.GetListPage();
        })
      },
      immediate: true,
    },
    bizRelInfos: {
      handler(newValue) {
        this.value = newValue?.map(i => i.bizId) ?? [];
        this.bizRelList = newValue?.map(i => {
          return {
            bizType: this.bizType,
            bizId: i.bizId,
            bizNo: i.eventNo,
          };
        }) ?? [];
      },
      immediate: true,
      deep: true,
    },
  },
  computed:{
    // otherOptionsList:非当前客户关联的事件
    otherOptionsList(){
      const list = this.bizRelInfos?.filter(v=>v.cusId && v.cusId != this.cusId) ?? []
      return list?.map(v=>{
        return {
          eventNo: v.bizNo,
          cusName: v.cusName,
          lmName: v.name,
          lmPhone: v.lmPhone,
          id:v.bizId
        }
      })
    },
    optionsList(){
      return [...this.otherOptionsList, ...this.list]
    }
  },
  methods: {
    toRelationEvent() {
      this.dialogVisible = true
      const secondEventId = this.from === 'imDetail' ? 'DETAIL_BTNS_GROUP' : undefined
      this.$track.clickStat(this.$track.formatParams('ASSOCIATED_EVENTS', null, secondEventId))
    },
    change(value) {
      this.bizRelList = [];
      for (let id of value) {
        let item = this.optionsList.find(item => item.id === id);
        if (item) {
          this.bizRelList.push({
            bizType: this.bizType,
            bizId: item.id,
            bizNo: item.eventNo,
          });
        }
      }
    },
    Switch() {
      this.dialogVisible = !this.dialogVisible;
    },
    Save() {
      // if (!this.bizRelList.length) {
      //   this.$message.error('请选择关联事件');
      //   return;
      // }
      ImApi.saveBizRel({
        conversationId: this.conversationId,
        bizRelList: this.bizRelList,
        bizType:'event'
      }).then(res => {
        if (res.code === 0) {
          this.dialogVisible = false;
          this.$emit('saveBizRel');
        }
      });
    },
    GetListPage() {
      if (!this.params.cusId) return;
      const query = { isOrderList: false };
      EventApi.queryEventPageList(query, this.params)
        .then(res => {
          if (res.succ && res.status == 0) {
            if (this.list.length) {
              this.list = this.list.concat(res.data.list);
            } else {
              this.list = res.data.list || [];
            }
          }
        })
        .catch(err => {
          console.error(err);
        })
        .finally(() => {});
    },
    filterMethod(value) {
      this.params.cusId = value;
      this.Timeout = setTimeout(() => {
        this.list = [];
        this.params.pageNum = 1;
        this.GetListPage();
        clearTimeout(this.Timeout);
      }, 400);
    },
    loadmoreList() {
      this.params.pageNum += 1;
      this.GetListPage();
    },
    cusNameReg(val){
      return val.replace(/<\/?a.*?>/g, '')
    }
  },
  directives: {
    loadmoreList: {
      bind(el, binding, vnode) {
        const SELECTWRAP = el.querySelector(
          '.el-select-dropdown .el-select-dropdown__wrap'
        );
        SELECTWRAP.addEventListener('scroll', function() {
          const CONDITION = this.scrollHeight - this.scrollTop <= this.clientHeight;
          if (CONDITION) {
            binding.value();
          }
        });
      },
    },
  },
};
</script>
<style>
.theme-default .el-select-dropdown.is-multiple .el-select-dropdown__item.selected.hover{
  background-color: rgb(245, 247, 250);
}
</style>
<style lang="scss" scoped>
.Info {
  font-size: 12px;
  div {
    height: 25px;
    display: flex;
    align-items: center;
  }
}
::v-deep .el-dialog__body {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: flex-start;
  padding: 20px 30px;
  box-sizing: border-box;
  .el-select{
    width: 100%;
    flex: 1;
  }
}
::v-deep .el-select-dropdown__item {
  height: auto;
}
.label {
  display: flex;
  align-items: center;
}
.associatedBox {
  display: inline-block;
}
.Info1{
  font-size: 14px;
  font-weight: 500;
}
.Info2{
  font-size: 12px;
  color: rgb(102, 102, 102);
}
</style>
